/**
 * Created by ZFL on 2017/9/13.
 */

var specDescId=[];   //所有规格的id
var comDescId1=[];   //
var comDescId2=[];
var seledIdArr=[];    //选中的规格组id
var seledIndexArr=[];   //存放选中的规格组位置
var inventoryId=0;    //库存id
var clickCount=0;


var vm=new Vue({
    el:"#hx_goodsEle",
    data:{
        lowestPrice:'',         //最低价格
        suggestedPrice:'',      //建议售价
        specPrice:'',           //规格页价格
        name:'',                //商品名称
        goodsId:'',             //商品id
        shareIcon:'',           //分享图片
        brand:{},               //品牌信息
        commentCount:0,         //评论总数
        commentList:[],         //评论数组
        roleId:0,               //角色ID
        storeName:'',           //店铺名字
        roleMoney:0,            //达人获得钱
        channelShow:false,      //判断是否是海淘商品
        goodDetailList:[],      //商品详情
        specImg:'',              //选中规格之后的图片
        goodsServiceList:[],     //服务条款
        specDescList:[],         //规格数组
        specId:'',               //规格ID
        specDescName :'一',         //默认规格
        backMoney:'' ,            //购买返多少欧币
        userDirectCommission:0,   //获得佣金
        inventoryNum:0,          //商品库存
        storesList:[],           //推荐店铺列表
        isShow:false,           //推荐店铺是否出现

    },
    methods:{
        //设置默认选中规格
        setSpec:function(){
            var _this = this;
            _this.specDescList.forEach(function(value,index){
                value.value.forEach(function(val,ind){
                    _this.$set(val,'seled',false);
                    _this.$set(val,'flag',false);
                })
            });

        },
        //选中规格事件
        selSpecFun:function(ele,item,index,ind){
            var _this = this;
            item.value.forEach(function(value,index){
                value.seled = false;
            });
            ele.seled = true;
            if(ele.specificationDetailImage.length>0){
                _this.specImg=ele.specificationDetailImage;
            }

            _this.specId = '';
            _this.specDescName = '';
            var seledCount=0;   //规格点击次数
            var seledIdArr2=[];
            clickCount++;
            for(var i=0;i<specDescId.length;i++){
                for(var j=0;j<specDescId[i].length;j++){
                    vm.specDescList[i].value[j].flag=false;

                }
            }

            var obj={};
            obj.index=index;
            obj.specificationDetailId=ele.specificationDetailId;
            obj.detailName=ele.detailName;
            //点击规格次数两次及以上时    对规格组进行  添加  删除 修改
            if(clickCount>1){
                //判断第二次点击是否是本身  如果是本身   取消选中
                if($.inArray(ele.specificationDetailId,seledIdArr)>-1){
                    var num=$.inArray(ele.specificationDetailId,seledIdArr);
                    seledArr.splice(num,1);
                    seledIdArr.splice(num,1);
                    seledIndexArr.splice(num,1)
                    ele.seled=false;
                    if(seledIdArr.length==0){
                        clickCount=0;
                    }

                }else{
                    //判断点击是否是同一行   如果同一行 进行替换    不属于同一行   则加入规格组
                    if($.inArray(index,seledIndexArr)==-1&&$.inArray(ele.specificationDetailId,seledIdArr)==-1){
                        seledArr.push(obj);
                        seledIdArr.push(ele.specificationDetailId);
                        seledIndexArr.push(index);
                    }else if($.inArray(index,seledIndexArr)!==-1&&$.inArray(ele.specificationDetailId,seledIdArr)==-1){
                        var num=$.inArray(index,seledIndexArr);
                        seledArr[num]=obj;
                        seledIdArr[num]=ele.specificationDetailId;
                        seledIndexArr[num]=index;
                        //console.log(obj)
                    }
                }

            }else{
                //如果只点击了一次   则直接加入规格组
                seledArr.push(obj);
                seledIdArr.push(ele.specificationDetailId);
                seledIndexArr.push(index);
            }
            //选中一个规格   就要在视图的界面显示
            seledArr.forEach(function(val,ind){
                _this.specDescName += val.detailName+' ';
                _this.specId += val.specificationDetailId;
                if(ind!= _this.specDescList.length-1){
                    _this.specId += ',';
                }
            })

            seledCount=seledIndexArr.length;




            //如果选中了一个规格
            if(seledCount==1) {
                var specIndex =seledArr[0].index;
                var arr1=[];
                var arr2=[];
                for(var m=0;m<seledArr.length;m++){
                    arr1.push(seledArr[m].specificationDetailId)
                }
                //判断其他行的规格是否能选   判断选中的规格组是否在能组合的规格组中
                for(var j=0;j<comDescId2.length;j++) {
                    if (isContained(arr1,comDescId2[j]) == true) {
                        for (var i = 0; i < comDescId2[j].length; i++) {
                            getCoordinate(comDescId2[j][i], specDescId)
                        }
                    }
                }
                //判断同一行的其他规格是否能点亮
                for (var i = 0; i < specDescId[specIndex].length; i++) {
                    if (seledArr[0].specificationDetailId!==specDescId[specIndex][i]) {
                        arr2[specIndex] = specDescId[specIndex][i];
                        console.log(arr2)
                        for (var m = 0; m < comDescId2.length; m++) {
                            isContained(arr2, comDescId2[m]);
                            //console.log(arr2)
                            if (isContained(arr2, comDescId2[m]) == true) {
                                for (var j = 0; j < comDescId2[m].length; j++) {
                                    getCoordinate(specDescId[specIndex][i], specDescId)

                                }

                            }
                        }
                    }

                }
            }else if(seledCount>1){
                //当选中的规格大于一个时
                var arr1=[];
                var arr2=[];
                for(var m=0;m<seledIdArr.length;m++){
                    arr1[m]=seledIdArr[m];
                    arr2[m]=seledIdArr[m];

                }
                for(var j=0;j<comDescId2.length;j++) {
                    if (isContained(arr1,comDescId2[j]) == true) {
                        console.log(comDescId2[j])
                        for (var i = 0; i < comDescId2[j].length; i++) {
                            getCoordinate(comDescId2[j][i], specDescId);
                        }
                    }
                }

                for(var i=0;i<seledCount;i++){
                    var specInd =seledArr[i].index;
                    for(var j=0;j<specDescId[specInd].length;j++){
                        if(seledArr[i].specificationDetailId!==specDescId[specInd][j]){
                            arr2[i]=specDescId[specInd][j];
                            for (var m = 0; m < comDescId2.length; m++) {
                                isContained(arr2,comDescId2[m]);
                                if (isContained(arr2,comDescId2[m]) == true) {
                                    getCoordinate(comDescId2[m][specInd],specDescId);

                                }
                            }

                        }
                        for(var m=0;m<seledIdArr.length;m++){
                            arr2[m]=seledIdArr[m];
                        }

                    }
                }
            }else if(seledCount==0){
                _this.specDescName='-'
                isInvertory();
            }
            if(seledCount==vm.specDescList.length){
                var seledSortArr=[];
                _this.specDescName='';
                _this.specId='';
                for(var i=0;i<seledArr.length;i++){
                    seledSortArr[seledArr[i].index]=seledArr[i]
                }
                seledSortArr.forEach(function(val,ind){
                    _this.specDescName += val.detailName+' ';
                    _this.specId += val.specificationDetailId;
                    if(ind!= _this.specDescList.length-1){
                        _this.specId += ',';
                    }
                })
                InventoryNumber(_this.specId);//判断数量
            }else{
                vm.inventoryNum=0;
                $('input[name="quantity"]').val(1);
                $('.shop-buy-number-control .decrease i').removeClass('active');
                vm.isShow=false;
                vm.specPrice=vm.lowestPrice;
            }

        },

        getTrends:function(){
        },
        //为店铺列表添加是否选中字段
        isSeleStore:function(){
            var _this=this;
            this.storesList.forEach(function(value,index){
                _this.$set(value,'selected',false)
                if(index==0){
                    value.selected=true;
                    vm.specPrice=divideNumber(value.salePrice,100);
                    vm.inventoryNum=value.inventoryNum;
                    inventoryId=value.inventoryId;
                    goods_obj.productId =value.productId;//货品ID
                    goods_obj.inventoryId =value.inventoryId;//库存ID
                    goods_obj.storeId = value.storeId;//店铺ID
                    goods_obj.inventoryNum = value.inventoryNum; //库存数
                }
            })
        },
        //选中推荐店铺事件
        seleStore:function(value){
            this.storesList.forEach(function(val,ind){
                val.selected=false;
            })
            value.selected=true;
            this.specPrice=divideNumber(value.salePrice,100);
            vm.inventoryNum=value.inventoryNum;
            inventoryId=value.inventoryId;
            goods_obj.productId =value.productId;//货品ID
            goods_obj.inventoryId =value.inventoryId;//库存ID
            goods_obj.storeId = value.storeId;//店铺ID
            goods_obj.inventoryNum = value.inventoryNum; //库存数


        }
    },
    filters:{
        unitConFun:function(val){
            return divideNumber(val,100)
        }
    }




})

function getCoordinate(val,arr){
    for(var i=0;i<arr.length;i++){
        for(var j=0;j<arr[i].length;j++){
            if(val==arr[i][j]){
                vm.specDescList[i].value[j].flag=true;

            }


        }
    }
}
function isContained(arr1,arr2){
    var aStr = arr2.toString();
    for(var i = 0, len = arr1.length; i < len; i++){
        if(aStr.indexOf(arr1[i])== -1&&arr1[i]!==undefined){
            return false;
        }else{

        }
    }
    return true;
}
var seledArr=[];   //选中的规格组
var noInverArr=[];    //没有库存的规格组
var agio = '';    //佣金类型 分享出来的商品
var goodsId =1;  //商品ID
var userId = 0;  //用户ID
var pageNum = 1;
var pageSize = 10;
var loading = false;
var productNum = '';    //商品库存
var productName = '';   //商品规格与分类名字
var goods_obj = {};     //商品信息
var shareUserId = '';   //分享人ID
var userGoodsId= $.getPara('userGoodsId');
function appInit(){
    PageInit();
}
//滚动加载商品评论
window.onscroll = function(){
    var scr = $(window).scrollTop();
    var clientH = document.body.clientHeight;
    var scrollH = document.body.scrollHeight;
    if(scr+clientH == scrollH){
        if(loading) return;
        loading = true;
        pageNum++;
        //YDUI.dialog.loading.open('正在加载...');
        setTimeout(function(){
            getGoodsComment();
        },100)
    }
};

function PageInit(){
    //getLocation();   //获得地理位置
    //var talentId=0;   分享人id
    if($.getPara('goodId')!=''){
        goodsId = $.getPara('goodId');
    }
    if(com_obj.userId!= 0){
        userId = com_obj.userId;
        if($.getStorage('xm_uData')){
            vm.level = JSON.parse($.getStorage("xm_uData")).level;
            if($.getPara('shareUserId') == '' && vm.level >=200){
                vm.roleShow = true;
            }
        }
    }
    if($.getPara("talentId")!=""){
        talentId=$.getPara("talentId");
    }
    if($.getPara('storeUserId')!=''){
        talentId=$.getPara("storeUserId");
        //加载店铺里的商品详情
        shareStoregoods();

    }else if($.getPara('shareGoodsId')!=''&&$.getPara('talentId')!=""){
        //加载分享的商品详情
        shareGoods();
    }else if($.getPara('goodsId')!=''){
        goodsId= $.getPara('goodsId');
        talentId=$.getPara("talentId");
        initApi();   //加载分享的期详情(普通期)
    }else{

    }

    //获取分享人的用户ID
    if($.getPara('shareUserId')!= ''){
        shareUserId = $.getPara('shareUserId');
    }



}
var userlatitude=0;  //用户所在纬度
var userlongitude=0;  //用户所在经度

var storelatitude=0;  //商家所在纬度
var storelongitude=0;  //商家所在经度


/***************************************
 由于Chrome、IOS10等已不再支持非安全域的浏览器定位请求，为保证定位成功率和精度，请尽快升级您的站点到HTTPS。
 ***************************************/
var map, geolocation;
//加载地图，调用浏览器定位服务
map = new AMap.Map('con', {
    resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
    geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition:'RB'
    });
    map.addControl(geolocation);
    geolocation.getCurrentPosition();
    AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
    AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
});
//解析定位结果
function onComplete(data) {
    userlatitude=data.position.getLat();
    userlongitude=data.position.getLng();
}
//解析定位错误信息
function onError(data) {

    document.getElementById('tip').innerHTML = '定位失败';
}

//banner轮播图
function swiperFun(){
    var swiper = new Swiper('.swiper-container', {
        pagination:'.swiper-pagination',
        //loop:true,
        //autoplay:3000,
        paginationClickable: true,
        longSwipesRatio: 0.3,
        touchRatio:1,
        observer:true,//修改swiper自己或子元素时，自动初始化swiper
        observeParents:true,//修改swiper的父元素时，自动初始化swiper


    });
}
//加载普通商品详情   分享期商品详情
function initApi(){
    var obj ={};
    obj.goodId = goodsId;

    if($.getPara("agio")!=""){
        obj.agio = agio;
    }
    if(com_obj.userId && com_obj.userId > 0){
        obj.userId=com_obj.userId
    }
    if($.getPara("talentId")!=""){
        obj.shareUserId=$.getPara("talentId");
    }
    $.ajaxHandler({
            model: function () {
                console.log(obj)
                return obj;
            },
            visibleTime: 0,
            visible:'show',
            dataType: "json",
            api: 'yg_baijiaappgoods/goods/getGoodsById',
            success: function (result) {
                if(result.code == 10000){
                    var data = result.data;
                    goods_obj.brandId = data.brandId;


                    vm.goodsId=data.goodsId;
                    goodsId=data.goodsId;
                    getGoodsComment();
                    //加载轮播图
                    var html = '';
                    //视频
                    if(data.videos!==null){
                        data.videos.forEach(function(value,index){
                            html='<div class="swiper-slide"><video controls autoplay><source src='+value.videoUrl+'></video></div>';
                            $('.swiper-wrapper').append(html);

                        })
                    }
                    //图片
                    data.goodNavigateList.forEach(function(value,index){
                        html='<div class="swiper-slide"><img src='+value.navigateImage+' alt=""></div>';
                        $('.swiper-wrapper').append(html);
                    })
                    vm.carouselVideos=data.videos;
                    vm.carouselImgs=data.goodNavigateList;

                    swiperFun();    //轮播图
                    vm.goodsServiceList = data.goodsServiceList;//服务条款
                    vm.backMoney = data.scoreRate * divideNumber(data.lowestPrice,100);
                    vm.shareIcon = data.goodNavigateList[0].navigateImage;  //分享到朋友圈和好友的icon
                    //商品详情

                    data.goodDetailList.forEach(function(value,index){
                        vm.goodDetailList.push(value);

                    });
                    vm.lowestPrice = divideNumber(data.lowestPrice,100);
                    vm.suggestedPrice = divideNumber(data.suggestedPrice,100);
                    vm.specPrice=divideNumber(data.lowestPrice,100);
                    vm.specImg = data.goodNavigateImage;   //默认规格图片

                    if(vm.suggestedPrice <= vm.lowestPrice){
                        $('.original-price').hide();
                    }
                    vm.name = data.name;

                    vm.storeName = data.storeName;

                    vm.brand = data.brand;
                    getSpec();


                    if($.getPara("talentId")!=""){//分享商品只能购买，不能加入购物车
                        $(".add-shop").hide();
                        $(".goods-shop").hide();
                    }
                }else{
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        }
    );
}
//加载分享商品详情
function shareGoods() {
    var obj={};
    obj.userId=com_obj.userId;
    //obj.userId=0;
    obj.shareGoodsId = $.getPara("shareGoodsId");
    $.ajaxHandler({
        model: function () {
            return obj;
        },
        visibleTime: 0,
        visible:'show',
        dataType: "json",
        api: 'yg_baijiaappgoods/shareGoods/getGoodsByShare',
        success: function (result) {

            if(result.code == 10000){
                var data = result.data;
                goods_obj.brandId = data.brandId;
                var roleMoney = divideNumber(data.userDirectCommission,100) * divideNumber(data.goodsCommission.commission,100) * divideNumber(data.lowestPrice,100);
                vm.roleMoney= divideNumber(parseInt(roleMoney * 100),100);
                vm.goodsId=data.goodsId;
                goodsId=data.goodsId;

                vm.userDirectCommission=data.userDirectCommission;

                getGoodsComment();
                //加载轮播图
                var html = '';
                //视频
                if(data.videos!==null){
                    data.videos.forEach(function(value,index){
                        html='<div class="swiper-slide"><video controls autoplay><source src='+value.videoUrl+'></video></div>';
                        $('.swiper-wrapper').append(html);

                    })
                }
                //图片
                data.goodNavigateList.forEach(function(value,index){
                    html='<div class="swiper-slide"><img src='+value.navigateImage+' alt=""></div>';
                    $('.swiper-wrapper').append(html);
                })


                swiperFun();    //轮播图
                vm.goodsServiceList = data.goodsServiceList;//服务条款
                vm.backMoney = data.scoreRate * divideNumber(data.lowestPrice,100);
                vm.shareIcon = data.goodNavigateList[0].navigateImage;  //分享到朋友圈和好友的icon
                //商品详情

                data.goodDetailList.forEach(function(value,index){
                    vm.goodDetailList.push(value);

                });
                vm.lowestPrice = divideNumber(data.lowestPrice,100);
                vm.specPrice=divideNumber(data.lowestPrice,100);
                vm.specImg = data.goodNavigateImage;   //默认规格图片
                vm.suggestedPrice = divideNumber(data.suggestedPrice,100);
                if(vm.suggestedPrice <= vm.lowestPrice){
                    $('.original-price').hide();
                }
                vm.name = data.name;

                vm.storeName = data.storeName;

                vm.brand = data.brand;
                getSpec();

                if($.getPara("talentId")!=""){//分享商品只能购买，不能加入购物车
                    $(".add-shop").hide();
                    $(".goods-shop").hide();
                }
            }else{
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}

//加载店铺里的商品详情
function shareStoregoods(){
    $.ajaxHandler({
        model:function(){
            var obj={};
            obj.userGoodsId=userGoodsId;
            return obj;
        },
        visibleTime:0,
        dataType: "json",
        visible:'hide',
        api:'/yg_baijiaappgoods/goods/getUserGoodsDetail',
        success:function(result){
            if(result.code == 10000){
                var data = result.data;
                goods_obj.brandId = data.brandId;


                vm.goodsId=data.goodsId;
                goodsId=data.goodsId;
                getGoodsComment();
                //加载轮播图


                //加载轮播图
                var html = '';
                //视频
                if(data.videos!==null){
                    data.videos.forEach(function(value,index){
                        html='<div class="swiper-slide"><video controls autoplay><source src='+value.videoUrl+'></video></div>';
                        $('.swiper-wrapper').append(html);

                    })
                }
                //图片
                data.goodNavigateList.forEach(function(value,index){
                    html='<div class="swiper-slide"><img src='+value.navigateImage+' alt=""></div>';
                    $('.swiper-wrapper').append(html);
                })

                swiperFun();    //轮播图
                vm.goodsServiceList = data.goodsServiceList;//服务条款
                vm.backMoney = data.scoreRate * divideNumber(data.lowestPrice,100);
                vm.shareIcon = data.goodNavigateList[0].navigateImage;  //分享到朋友圈和好友的icon
                //商品详情

                data.goodDetailList.forEach(function(value,index){
                    vm.goodDetailList.push(value);

                });
                vm.lowestPrice = divideNumber(data.lowestPrice,100);
                vm.suggestedPrice = divideNumber(data.suggestedPrice,100);
                vm.specPrice=divideNumber(data.lowestPrice,100);
                vm.specImg = data.goodNavigateImage;   //默认规格图片
                if(vm.suggestedPrice <= vm.lowestPrice){
                    $('.original-price').hide();
                }
                vm.name = data.name;

                vm.storeName = data.storeName;

                vm.brand = data.brand;
                getSpec();

                if($.getPara("talentId")!=""){//分享商品只能购买，不能加入购物车
                    $(".add-shop").hide();
                    $(".goods-shop").hide();
                }
            }else{
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    })
}



//得到规格
function getSpec(){
    $.ajaxHandler({
        model:function(){
            var obj={};
            obj.goodsId=goodsId;
            obj.userId=userId;
            return obj;
        },
        visibleTime: 0,
        visible:'show',
        dataType: "json",
        api: '/yg_baijiaappgoods/product/getSpecDesc',
        success:function(res){
            if(res.code==10000){
                var data=res.data;
                vm.specDescList=data.specInfo;
                var comDescList=data.combination;
                vm.setSpec();
                for(var m=0;m<comDescList.length;m++){
                    var comSpecArr=[];
                    comSpecArr=comDescList[m].specInfo.split(',')

                    for(var n=0;n<comSpecArr.length;n++){
                        if(!comDescId1[n]){
                            comDescId1[n]=[]
                        }

                        comDescId1[n].push(comSpecArr[n])
                    }
                    comDescId2.push(comSpecArr)
                }
                for(var i=0;i<vm.specDescList.length;i++){

                    if(!specDescId[i]){
                        specDescId[i]=[];
                    }
                    for(var j=0;j<vm.specDescList[i].value.length;j++){
                        specDescId[i].push(vm.specDescList[i].value[j].specificationDetailId)

                    }

                }

            }
        }

    })



}

//判断哪些规格没有库存

function isInvertory(){
    for(var i=0;i<specDescId.length;i++){
        for(var j=0;j<specDescId[i].length;j++){
            if($.inArray(String(specDescId[i][j]),comDescId1[i])!=-1){
                vm.specDescList[i].value[j].flag=true;

            }else{
                noInverArr.push(vm.specDescList[i].value[j].specificationDetailId)

            }
        }
    }
}

//商品评论
function getGoodsComment(){
    $.ajaxHandler({
        model: function () {
            var obj = {};
            obj.goodId = goodsId;
            obj.pageNum = pageNum;
            obj.pageSize = pageSize;
            vm.goodsId=goodsId;
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        visible:'hide',
        api:'yg_baijiaapporder/goodsComment/listGoodsCommentByGoodId',
        success: function (result) {
            if(result.code == 10000){
                var data = result.data;
                vm.commentCount = data.count;  //评论总数
                if(data.list.length > 0){
                    // 加载数据
                    loading = false;
                    data.list.forEach(function(value,index){
                        value.imgArr = [];
                        if(value.image1 != ''){
                            value.imgArr.push(value.image1);
                        }
                        if(value.image2 != ''){
                            value.imgArr.push(value.image2);
                        }
                        if(value.image2 != ''){
                            value.imgArr.push(value.image3);
                        }
                        vm.commentList.push(value);
                    });
                    //console.log(vm.commentList);
                    //表示这是最后一页数据
                    if(data.pageCount == pageNum){
                        loading = true;
                    }
                }else {
                    loading = true;
                }
            }else{
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}




//点击购买  弹出规格页   去选择规格购买
function buyNow(){
    isInvertory();
    $('video').hide();
    var userPhone=0;
    if($.getStorage('xm_uData')){
        userPhone=JSON.parse($.getStorage('xm_uData')).userName;
    }
    if(com_obj.userId && com_obj.userId>0&&userPhone.length==11){
        $('#shop-layer-id').addClass('back-show');
        $('.shop-fixed').addClass('back-show animation-slide-bottom');
        $('.html').css({height:"100%"});
        $('.goods').css({height:"100%",overflow:"hidden"});
    }else if(userPhone.length!=11&&com_obj.userId>0){
        //用户登录(例如扫码领红包后 在进入微商城可以自动登录)  但没有绑定手机号
        var httpUrl = window.location.href;
        window.location.href = '../user/bindPhone.html?href='+httpUrl+'';
    }else if(com_obj.userId==0){
        var httpUrl = window.location.href;
        window.location.href = '../user/user_login.html?href='+httpUrl+'';
    }
}




function goodsBuy(){
    if(userId&&userId > 0){
        var  para = {};
        para.activityType  = 0;     //活动类型
        para.userId = userId;//购买者用户Id
        para.applywelfareId  = 0;   //福利社ID
        if($.getPara('applywelfareId')!=''){
            para.applywelfareId = $.getPara('applywelfareId');
        }
        para.shareActivityId = 0; //分享活动id
        if($.getPara('shareActivityId')!=''){
            para.shareActivityId= $.getPara('shareActivityId');
        }
        var array =[];
        var obj ={};
        obj.brandId = goods_obj.brandId;    //品牌id
        obj.goodId = parseInt(goodsId);     //商品Id
        obj.inventoryId = goods_obj.inventoryId;    //库存ID
        obj.quantity= parseInt($('input[name="quantity"]').val());    //数量
        obj.storeId=goods_obj.storeId;
        if($.getPara('shareSerialId')!=''){
            obj.shareSerialId  = $.getPara('shareSerialId');//分享品牌期咨询id
        }
        //分享商品的分享人id  以及分享期的分享人ID
        if($.getPara('talentId')!=''){

            if($.getPara('talentId')!= com_obj.userId && $.getPara('talentId')> 0){
                obj.talentId  = $.getPara('talentId');//分享人id
            }
        }
        //分享店铺 的分享人Id
        if($.getPara('storeUserId')!=''){

            if($.getPara('storeUserId')!= com_obj.userId && $.getPara('storeUserId')> 0){
                obj.talentId  =$.getPara('storeUserId');//分享人id
            }
        }
        if($.getPara('shareGoodsId')!=''){
            obj.talentShareGoodId  = $.getPara('shareGoodsId');//商品分享id
        }
        if($.getPara('serialId')!=''){
            obj.shareSerialId  = $.getPara('serialId');//分享期Id
        }
        array.push(obj);
        para.lat=userlatitude;
        para.lon=userlongitude;
        para.noFilter=1;
        para.goodsSimpleVoList = array;
        para.reqType = 1;//	0:app,1:h5

        $.setStorage('orderObject',para);

        if($.isWX() && !$.getStorage("xmOpenid")){
            //获取Code


            window.location.href  = '../user/getOpenid.html?openid=openid';

        }else{
            //非微信浏览器中
            window.location.href= $.wxApi()+'b2c/pay/goodsPay.html';
        }
    }else{
        //YDUI.dialog.toast('我在这',1000)
        //var httpUrl = window.location.href;
        //window.location.href = '../../user/user_login.html?href='+httpUrl+'';
    }

}
//得到商品库存数
function InventoryNumber(specInfo){
    $.ajaxHandler({
        model: function () {
            var obj ={};
            obj.goodId = goodsId;
            obj.specInfo = specInfo;
            if(userId != 0){
                obj.userId = userId;
            }
            //分享商品
            if(shareUserId != ''){
                obj.shareUserId = shareUserId;
            }
            console.log(obj)
            return obj;
        },
        visibleTime: 0,
        visible:'hide',
        dataType: "json",
        api: 'yg_baijiaappgoods/product/getProductByGoodIdAndSpecInfo',
        success: function (result) {
            var data = result.data;
            if (result.code == 10000) {
                productNum = data.inventoryNum;
                vm.inventoryNum=data.inventoryNum;
                if(productNum > 0) {
                    goods_obj.productId = data.productId;//货品ID
                    goods_obj.inventoryId = data.inventoryId;//库存ID
                    goods_obj.storeId = data.storeId;//店铺ID
                    goods_obj.productType = data.produtType;//商品类型
                    goods_obj.inventoryNum = data.inventoryNum; //库存数
                    //$('.add-shop-price').text(fmoneyStr(divideNumber(data.salePrice, 100)));//售价

                }
                recommendStores(data.inventoryId)
            }else if(result.code == 20000) {
                $.toast('异常',"text");
                productNum = 0;
            }else{
                $.toast(''+result.message+'',"text");
                productNum = 0;
            }
        }
    });
}

//推荐店铺
function recommendStores(invenId){
    $.ajaxHandler({
        model:function(){
            var obj={};
            obj.inventoryId=invenId;
            //obj.latitude=31.243463;
            //obj.longitude=121.452172;
            obj.latitude=userlatitude;
            obj.longitude=userlongitude;
            obj.userId=userId;
            console.log(obj);
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        visible:'hide',
        api:'/yg_baijiaappgoods/store/productStoreScreen',
        success:function(res){
            if(res.code==10000){
                if(res.data.length>0){
                    vm.storesList=res.data;
                    vm.isSeleStore();   //为推荐店铺添加是否选中状态
                    vm.isShow=true;
                }

            }
        }
    })
}


//数量绑定
function  ProductCode(type){
    var num = parseInt($('input[name="quantity"]').val());

    if(type==1){
        //++

        if(num>=vm.inventoryNum&&seledArr.length==vm.specDescList.length){
            //$('.shop-buy-number-control .increase i').addClass('active');

            YDUI.dialog.toast('没库存了',1000);
        }else if(seledArr.length!==vm.specDescList.length){
            YDUI.dialog.toast('请选择商品规格',1000);

        }else{
            $('input[name="quantity"]').val(num+1);
            $('.shop-buy-number-control .decrease i').removeClass('active');
        }

    }else if(type==0){
        //--
        if(num !="" && num > 1){
            $('input[name="quantity"]').val(num-1);
        }
        if($('input[name="quantity"]').val() == 1){
            $('.shop-buy-number-control .decrease i').addClass('active');
        }
    }
}

//选择规格后进行购买
function SelectAddShop(){
    //每种规格都被选中后且购买的数量不大于库存且出现推荐店铺
    var buyNum=parseInt($('input[name="quantity"]').val());
    if(vm.storesList!==null){
        if(seledArr.length==vm.specDescList.length&&buyNum<=vm.inventoryNum&&vm.storesList.length>0){

            //立即购买
            goodsBuy();
        }
    }



}


//加入购物车layer关闭
function clearShop(){
    $('#shop-layer-id').removeClass('back-show');
    $('.shop-fixed').removeClass('back-show animation-slide-bottom');
    $('html').css({height:"auto"});
    $('.goods').removeAttr("style");
    $('video').show();
}
//打开服务条约
function deliverPact(){
    $('#server-layer-id').addClass('back-show');
    $('.server-fixed').addClass('back-show animation-slide-bottom');
    $(".goods-foot").slideUp();
    $('.html').css({height:"100%"});
    $('.goods').css({height:"100%",overflow:"hidden"});
}
//关闭服务条款
function cloasePact() {
    $('#server-layer-id').removeClass('back-show');
    $('.server-fixed').removeClass('back-show animation-slide-bottom');
    $(".goods-foot").slideDown();
    $('html').css({height:"100%"});
}



//显示灰色 jQuery 遮罩层
function showBg() {
    var bh = $("body").height();
    var bw = $("body").width();
    $("#fullbg").css({
        height:bh,
        width:bw,
        display:"block",
    });
    $("#dialog").show()
    $('body').css("overflow","hidden")
    ;

}
//关闭灰色 jQuery 遮罩
function closeBg(){
    $("#fullbg,#dialog").hide();
    $('body').css("overflow","visible")
}

//function clear(e){
//    e.preventDefault();
//    window.localStorage.clear();
//}

